package com.lvbey.www;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;

public class Tool {

    public static double rgb2GrayScale(int rgb) {
        int red = (rgb >> 16) & 0xFF;
        int green = (rgb >> 8) & 0xFF;
        int blue = rgb & 0xFF;
        return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
    }


    public static char grayScale2Char(double grayScale, String artCharList) {
        return grayScale2Char(grayScale, artCharList.toCharArray());
    }

    /**
     * @param grayScale
     * @param artCharList darker to lighter
     * @return
     */
    public static char grayScale2Char(double grayScale, char[] artCharList) {
        if (null == artCharList || artCharList.length == 0) {
            throw new IllegalArgumentException("artCharList cannot be empty.");
        }
        int index = (int) (Math.round(grayScale * artCharList.length / 256) - 1);
        if (index < 0) {
            return artCharList[0];
        }
        return artCharList[index];
    }


    public static BufferedImage resize(BufferedImage source, int targetW,
                                       int targetH) {
        int type = source.getType();
        BufferedImage target = null;
        double sx = (double) targetW / source.getWidth();
        double sy = (double) targetH / source.getHeight();
        if (sx < sy) {
            sx = sy;
            targetW = (int) (sx * source.getWidth());
        } else {
            sy = sx;
            targetH = (int) (sy * source.getHeight());
        }
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
                    targetH);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else
            target = new BufferedImage(targetW, targetH, type);
        Graphics2D g = target.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
    }
}
